package com.android.myapplication.view.media;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import com.android.myapplication.view.view.ClockView;

import androidx.annotation.Nullable;

public class AudioView extends View {
    public byte[] list;
    Paint paint;
    int w = 10;

    public static AudioView audioView;

    public AudioView(Context context) {
        super(context);
        init();

    }

    public AudioView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AudioView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {
        audioView = this;
        setBackgroundColor(Color.WHITE);

        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(w);
    }

    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (list != null) {

            int y  = getHeight() / 2;
            int x = 100;
            int interval = list.length / ((getWidth() - x) / 10);
            int index = 0;
            paint.setStrokeWidth(1);
            paint.setTextSize(dp2px(getContext(), 15));
            canvas.drawLine(0, 1, getWidth(), 1, paint);
            canvas.drawText("高度:" + getHeight() / 2, 0, 0, paint);
            int y127= (getHeight()/2 - 127);
            canvas.drawLine(0, y127, getWidth(), y127, paint);
            canvas.drawText("高度:127", 0, y127, paint);
            paint.setStrokeWidth(w);
            for (int i = 0; i < list.length; i+=interval,index++) {
                canvas.drawLine(index * w, y, (index) * w, y - list[index], paint);
            }
        }
    }

    public void setList(byte[] list) {
        if (this.list == null || this.list.length != list.length) {
            this.list = new byte[list.length];
        }
        System.arraycopy(list, 0, this.list, 0, list.length);
        postInvalidate();
    }
    public static int dp2px(Context context, float dp) {
        final float density = context.getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5);
    }

    public static int px2dp(Context context, float px) {
        final float density = context.getResources().getDisplayMetrics().density;
        return (int) (px / density + 0.5);
    }

}
